package com.gege.homework2.service;

import com.gege.model.Order;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * @author gechenpeng
 * @date 2021-05-20
 */
@Service
public class OrderService {

    @Autowired
    private DataSource dataSource;

    public void addOrderInBulk(List<Order> orderList) {
        List<List<Order>> orderBulk = Lists.partition(orderList, 1000);

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);

            String sql = "INSERT INTO tb_order (user_id, create_at, total_amount) VALUES (?, now(), ?)";
            preparedStatement = connection.prepareStatement(sql);

            for (List<Order> orders : orderBulk) {
                for (Order order : orders) {
                    preparedStatement.setLong(1, order.getUserId());
                    preparedStatement.setBigDecimal(2, order.getTotalAmount());

                    preparedStatement.addBatch();
                }

                preparedStatement.executeBatch();
                preparedStatement.clearBatch();
            }

            connection.commit();
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            try {
                if (null != preparedStatement) {
                    preparedStatement.close();
                }

                if (null != connection) {
                    connection.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e.getMessage());
            }
        }
    }
}
